import "whatwg-fetch";
import { getToken } from "@/util/tokenStorage";
import router from "@/router"
import { LOGIN } from "@/router/name";

/**
 * 判断异常情况
 */

 const checkStatus =  async response => {
    if(response.status >= 200 && response.status < 300){
    return response;
    }
    let responseBody = {};
    try{
    responseBody = await response.json();
    } catch (e){
    console.log(e);
    }
    console.log(responseBody);
    const error = new Error();
    error.name = response.status;
    error.message = responseBody.message;
    error.body = responseBody;
    throw error;
 };

/**
 * 发起请求 返回一个Promise对象 
 * */ 
export default async function request(url,options){
    // const defaultOptions = {
    //     credentials: "include"
    // };
    const newOptions = { ...options };
    if (
    newOptions.method === "POST" ||
    newOptions.method === "PUT" ||
    newOptions.method === "DELETE"
    ) {
    if (!(newOptions.body instanceof FormData)) {
        newOptions.headers = {
        Accept: "application/json",
        "Content-Type": "application/json; charset=utf-8",
        ...newOptions.headers
        };
        newOptions.body = JSON.stringify(newOptions.body);
    } else {
        // newOptions.body is FormData
        newOptions.headers = {
        Accept: "application/json",
        ...newOptions.headers
        };
    }
    }
    const token = getToken();
    if (token) {
    newOptions.headers = {
        ...newOptions.headers,
        Authorization: token
    };
    }
    console.log(newOptions);
    const response = await fetch(url, newOptions);
    try {
    await checkStatus(response);
    } catch (e) {
    if (e.name === 401) {
        router.push({ name: LOGIN });
    } else {
        throw e;
    }
    }

    if (response.status === 204) {
    return response.text();
    }
    const Authorization = await response.headers.get("Authorization");
    const body = await response.json();
    const header = {
    Authorization
    };

    return { ...body, _header: header };
} 
